//
//  ViewController.m
//  模拟买票(多个线程访问共享资源)
//
//  Created by 伍银荣 on 2021/8/20.
//  Copyright © 2021 com.WYR. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
//总票数
@property (nonatomic, assign) int ticketCount;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.ticketCount = 10;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];
    [thread start];
    
    NSThread *thread2 = [[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];
    [thread2 start];
}

//模拟买票的方法
- (void)sellTickets {
    //死循环
    while (YES) {
        //模拟耗时操作
        [NSThread sleepForTimeInterval:1]; //延迟1秒后执行后面的操作
        if (self.ticketCount > 0) {
            //加上一把同步锁(把读写绑定在一起,只要这次读写没有完成的话,锁是不会开的),多条线程按顺序的执行(同步执行)
            @synchronized (self) {
                self.ticketCount = self.ticketCount - 1;
                NSLog(@"剩余%d张票",self.ticketCount);
            }
        } else {
            NSLog(@"来晚了,票卖完了");
            break;
        }
    }
}


@end
